<?php


namespace utils;


class IpAddress
{

    public static function getIpInfo($ip)
    {
        $ip2region = new \Ip2Region();
        return $ip2region->simple($ip);
    }

    public static function getIpInfo_v1($ip)
    {
        $ch = curl_init();
        $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        // 转换编码
        $data = mb_convert_encoding($data, 'utf-8', 'GB2312');
        // 截取{}中的字符串
        $data = substr($data, strlen('({') + strpos($data, '({'), (strlen($data) - strpos($data, '})')) * (-1));
        // 将截取的字符串$data中的‘，’替换成‘&’   将字符串中的‘：‘替换成‘=’
        $data = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $data)));
        // 将字符串转换成数组格式
        parse_str($data, $addressInfo);
        // 返回ip归属地
        $info = explode(' ', $addressInfo['addr']);
        $data = [
            'city' => trim($info[0]),
            'isp' => trim($info[1]),
        ];
        return $data;
    }
}